<?php
include_once(MODPATH.'/common/logs.php');

/**
 * 
 * @author spring
 * @version 2014-6-7 上午10:38:35
 */
class  Delivery  extends Basic {

	/**
	 * 
	 * Description 往deliveryorders插入一条数据，手动新建出库单和导入自动生成盘亏出库
	 * @param field_type  bare_field_name
	 * @param array $condition  插入数据库的数据
	 * @return int 影响行数
	 */
	public  static function insert_delivery($condition=array()){
        include_once(MODPATH.'/common/logs.php');
        //$warehouse_id = Kohana::$config->get('warehouse')->warehouse_id;
		$condition['order_id']=0;
		$condition['op_time']=date('Y-m-d H:i:s');
		$condition['sku'] = strtoupper(trim($condition['sku']));
        $condition['supplier_id'] = $condition['supplier_id'] ? $condition['supplier_id'] : 0;
        $sku = $condition['sku'];
        $enterprise_dominant = intval($condition['enterprise_dominant']);
        $warehouseid = intval($condition['warehouseid']);
        $sql = "SELECT id,warehouse_quantity,use_quantity,supplier_id 
        FROM warehouseorders 
        WHERE sku='$sku' 
        AND (enterprise_dominant=$enterprise_dominant 
            OR enterprise_dominant=0) 
        AND warehouse_quantity>use_quantity 
        AND warehouseid=$warehouseid 
        ORDER BY enterprise_dominant desc, warehouse_date ASC";
        $res = DB::query(Database::SELECT,$sql)->execute('newerp')->as_array();
        if(empty($condition)) return false;

        $tempres = array();
        $quantity = $condition['quantity'];
        foreach ($res as $key => $value) {
            $tempquality = $value['warehouse_quantity'] - $value['use_quantity'] - $quantity;
            if ($tempquality >= 0) {
                $tempres[$key]['id'] = $value['id'];
                $tempres[$key]['supplier_id'] = $value['supplier_id'];
                $tempres[$key]['use_quantity'] = $value['use_quantity'] + $quantity;
                $tempres[$key]['quantity'] = $quantity;
                break;
            } else {
                $tempres[$key]['id'] = $value['id'];
                $tempres[$key]['supplier_id'] = $value['supplier_id'];
                $tempres[$key]['use_quantity'] = $value['warehouse_quantity'];
                $tempres[$key]['quantity'] = $value['warehouse_quantity'] - $value['use_quantity'];
                $quantity = $quantity - $tempres[$key]['quantity'];
            }

        }
		$common = new Service_common();
		$price = $common->get_sku_price($condition['sku']);

		$userid = User::active_user()->id;

		$db = Database::instance();
        $db->begin();
        try {
            foreach ($tempres as $data) {

                list($insert_id, $total_rows) = DB::insert('deliveryorders',
                    array('delivery_date','warehouseid','op_time','order_id','delivery_department','delivery_man','sku',
                        'sku_name','sku_standard','storage_position','quantity','single_price','money','cost','remark',
                        'type','supplier_id','enterprise_dominant'))
                    ->values(array($condition['delivery_date'],$condition['warehouseid'],$condition['op_time'],$condition['order_id'],
                        0,$userid,$condition['sku'],$condition['sku_name'],$condition['sku_standard'], $condition['storage_position'],
                        $data['quantity'],0,0,$price*$data['quantity'],$condition['remark'],$condition['type'],
                        $data['supplier_id'],$condition['enterprise_dominant']))
                    ->execute('newerp');
                $log_sql =  DB::insert('deliveryorders',
                    array('delivery_date','warehouseid','op_time','order_id','delivery_department','delivery_man','sku',
                        'sku_name','sku_standard','storage_position','quantity','single_price','money','cost','remark',
                        'type','supplier_id','enterprise_dominant'))
                    ->values(array($condition['delivery_date'],$condition['warehouseid'],$condition['op_time'],$condition['order_id'],
                        0,$userid,$condition['sku'],$condition['sku_name'],$condition['sku_standard'], $condition['storage_position'],
                        $data['quantity'],0,0,$price*$data['quantity'],$condition['remark'],$condition['type'],
                        $data['supplier_id'],$condition['enterprise_dominant']))
                    ->compile('newerp');
                if($insert_id){
                    logs::write_log($insert_id,'deliveryorders/insert',1,$log_sql);
                }else{
                    $db->rollback();
                    logs::write_log($insert_id, 'deliveryorders/insert',0,$log_sql, '特殊出库单创建失败！');
                    return false;
                }

                $update_res = DB::update('warehouseorders')->set(array('use_quantity' => $data['use_quantity'],'deliveryorders_id'=>$insert_id))
                    ->where('id', '=', $data['id'])->execute('newerp');
                $update_res_log = DB::update('warehouseorders')->set(array('use_quantity' => $data['use_quantity']))
                    ->where('id', '=', $data['id'])->compile('newerp');
                if ($update_res) {
                    logs::write_log($update_res, 'warehouseorders/update',1,$update_res_log);
                } else {
                    $db->rollback();
                    logs::write_log($update_res, 'warehouseorders/update',0,$update_res_log, '特殊出库单更新入库单可用量失败！');
                    return false;
                }

                //若不良出库，系统录入不良品仓数据
                if($condition['type']==50){
                    $udi = ORM::factory('unqualified');
                    $udi->invoice_date  =date('Y-m-d H:i:s');
                    $udi->deliveryorders_id =$insert_id;
                    $udi->sku = $condition['sku'];
                    $udi->sku_name = $condition['sku_name'];
                    $udi->sku_standard =$condition['sku_standard'];
                    $udi->storage_position = $condition['storage_position'];
                    $udi->quantity = $data['quantity'];
                    $udi->check_time = date('Y-m-d H:i:s');
                    $olderp_user_id =qualityaction::getskuname($condition['sku']);
                    $olderp_user_name = qualityaction::geterpname($olderp_user_id['oper']);
                    $newerp_user_id = qualityaction::getuserid($olderp_user_name);
                    $udi->purchase_man =$newerp_user_id;
                    $udi->quality_man = $userid;
                    $udi->warehouseid = $condition['warehouseid'];
                    //$udi->quality_remark =$condition['remark'].',良品出库进不良品仓，良品出库的出库单号是'.$insert_id;
                    $udi->quality_remark =$condition['remark'].',良品出库进不良品仓';
                    $udi->status =10;
                    $udi->save();
                }
            }

            $db->commit();
            return $insert_id;
        } catch (Exception $e) {
            $db->rollback();
            return false;
        }
	}
	
	/**
	 *
	 * Description 往deliveryorders插入一条数据,计划任务查询销量出库
	 * @param field_type  bare_field_name
	 * @param array $condition  插入数据库的数据
	 * @return int 影响行数
	 */
	public  static function insert_delivery1($condition=array()){
		$userid = User::active_user()->id;
		$condition['sku'] = strtoupper(trim($condition['sku']));
		$common = new Service_common();
		$price = $common->get_sku_price($condition['sku']);

		list($insert_id, $total_rows) = DB::insert('deliveryorders',
				array('delivery_date','op_time','order_id','orders_products_id','delivery_man','sku','sku_name','sku_standard','storage_position','quantity','single_price','money','cost','remark','type'))
				->values(array($condition['delivery_date'],$condition['delivery_date'],$condition['order_id'],$condition['orders_products_id'],$userid,strtoupper($condition['sku']),$condition['sku_name'],$condition['sku_standard'],
						$condition['storage_position'],$condition['quantity'],$condition['single_price'],$condition['quantity']*$condition['single_price'],$price*$condition['quantity'],$condition['remark'],$condition['type']))
						->execute('newerp');
				return   $total_rows;
	}
	
	
	
	
	
	
	/**
	 *
	 * Description 验证特殊出库上传的execl是否准确
	 * @param field_type  bare_field_name
	 * @param array $data  excel表格转化为二维数组
	 */
	public static function check_special_upload($data){
//		$tablename='inventories';
		$num = count($data);
		$result = array();
		$counter = 0;
		$sku_arr = array();
        $warehouse = Basic::get_warehouse_list();

		for($i=2;$i<=$num;$i++) {
			$sku_arr[] = strtoupper(trim($data[$i]['B']));
 		}
		//$sku_inv_arr 	= Warningtmp::get_inventory($sku_arr);

//		var_dump($sku_inv_arr);
//		exit();
        for($i=2;$i<=$num;$i++) {
			$type=trim($data[$i]['A']);//$type
			$sku=strtoupper(trim($data[$i]['B']));//$SKU
			$quantity=trim($data[$i]['C']);//$quantity
			$outDate=trim($data[$i]['D']);//$Date
			$remark=trim($data[$i]['E']);//$remark
            $warehouseid = trim($data[$i]['F']);
			//yuqing --去除看不懂的代码  重写检查库存量的代码
//			$pre= Pandian::getListInfoCondition(Report::getListPre($tablename),array('sku'=>$sku,'start_time'=>date('Y-m-d')),true,$tablename);
//			$datas=Pandian::getList(1,0,$pre);
//			$datas=Pandian::excute_data($datas,date('Y-m-d H:i:s'));
//			$quantity1=isset($datas[0]['quantity'])?$datas[0]['quantity']:0;
//			$quantity1 = ;

			if(!isset($type)||empty($type)){
				$counter ++;
				$result[$i]=0;continue;
				//self::alert('你输入的第'.$i.'行出库类型不能为空');
			}
			if(!isset($sku)||empty($sku)){
				$counter ++;
				$result[$i]=1;continue;
				//self::alert('你输入的第'.$i.'行SKU不能为空');
			}
			if(!preg_match('/^[1-9](\d+)?$/',$quantity)){
				$counter ++;
				$result[$i]=2;continue;
				//self::alert('你输入的第'.$i.'行数量不符合规则');
			}
			if(!isset($outDate)||empty($outDate)){
				//self::alert('你输入的第'.$i.'行日期不能为空');
				$counter ++;
				$result[$i]=3;continue;
			}
		    if(!preg_match('/^([1-2][0-9]{3})[\/|\-](0?[1-9]|10|11|12)[\/|\-]([1-2]?[0-9]|0[1-9]|30|31)$/',$outDate)){
  				$counter ++;
				$result[$i]=4;continue;
		    	//self::alert('你输入的第'.$i.'行日期不符合规则');
  		    }
			if(!Deliverycheck::check_sku($sku)){
				$counter ++;
				$result[$i]=5;continue;
				//self::alert('你输入的第'.$i.'行SKU有误');
			}
		    if(!self::deep_in_array(trim($type),self::get_delivery_status('deliveryorders','type'))){
				$counter ++;
				$result[$i]=6;continue;
		    	//self::alert('你输入的第'.$i.'行出库类型有误');
 			}

            if (!in_array(trim($warehouseid), array_keys($warehouse))) {
                $counter ++;
                $result[$i]=7;continue;
            }

            $inventory = Warningtmp::get_inventory_for_vmi($sku, $warehouseid);
            $sy = $inventory[$sku] ? $inventory[$sku] : 0 - $quantity;

 			if($sy < 0){
 				$counter ++;
				$result[$i]=8;continue;
 				//self::alert('你输入的第'.$i.'的数量超出库存量'.$quantity1);
 			}
		}
		$result['flag']=$counter;
		return $result;
		
	} 
	
		/**
		 * 
		 * Description   表格上传数据
		 * @param field_type  bare_field_name
		 * @param array $data excel表格转化为二维数组
		 * @return array 返回影响的行
		 */
		public static function do_special_upload($data){
			$num = count($data);
			$userid = User::active_user()->id;
			$lines=array();
			for($i=2;$i<=$num;$i++){
				$type=trim($data[$i]['A']);
				$type=self::getIntpyeByid($type);
				$sku=strtoupper(trim($data[$i]['B']));
				$quantity=trim($data[$i]['C']);
				$outDate=trim($data[$i]['D']);//$Date
				$remark=trim($data[$i]['E']).',手动上传出库';
				$warehouseid = trim($data[$i]['F']);
				$result=Deliverycheck::load_sku_info($sku, $warehouseid);
				$condition=array('delivery_date'=>date('Y-m-d H:i:s'),
				'order_id'=>0,
				'delivery_man'=>$userid,'sku'=>$sku,'sku_name'=>$result['products_name_cn'],'sku_standard'=>$result['size'],'storage_position'=>$result['products_place'],
				'quantity'=>$quantity,'warehouseid'=>$warehouseid,'remark'=>$remark,'type'=>$type);
				if(!self::insert_delivery($condition)){
					$lines[]=$num;
				}
			}
			return $lines;
		}
	
		
		public static function get_delivery($table,$id){
		 return DB::select()->from($table)->where('id','=',$id)->execute('newerp')->current();
		}
		
		
		public static  function update_delivery($condition){
			$old_num = $condition['re_quantity'];
			$do = ORM::factory('deliveryorder',$condition['id']);
			$money = $do->money/$old_num*$condition['quantity'];
			$cost = $do->cost/$old_num*$condition['quantity'];

			$total_rows=DB::update('deliveryorders')
			->set(array('quantity'=>$condition['quantity'],'money'=>$money,'cost'=>$cost,'delivery_date'=>$condition['delivery_date'],'type'=>$condition['type'],'remark'=>$condition['remark']))
			->where('id','=',$condition['id'])
			->execute('newerp');
			return $total_rows;
		}
		/**
		 * 
		 * Description 多维数组中是否有一个值
		 * @param field_type  bare_field_name
		 * @param mixed $value
		 * @param array $array 多维
		 * @return boolean 
		 */
		 
		private  static function deep_in_array($value, $array) {  
			 foreach($array as $item) {  
			        if(!is_array($item)) {  
			            if ($item == $value) { 
			                return true; 
			            } else { 
			                continue;  
			            } 
			        }  
			        if(in_array($value, $item)) { 
			            return true;     
			        } else if(self::deep_in_array($value, $item)) { 
			            return true;     
			        } 
			    }  
   		       return false;  
          }
         
          public static function  getIntpyeByid($type)
          {
          	/*switch ($type) {
          		case '盘亏':
          			return 20;
          			break;
          		case '礼物送人':
          			return 30;
          			break;
          		case '样品临时借出':
          			return 40;
          			break;
          		case '样品临时借出':
          			return 40;
          			break;
          		case '样品临时借出':
          			return 40;
          			break;}*/
							$st = ORM::factory('statusdic')->where('table','=','deliveryorders')->where('value','=',$type)->find();
							if($st->id!=''){
								return $st->number;
							}else{
								return 0;
							}
          	}
          
}
